import tensorflow as tf
from tensorflow import keras
import matplotlib.pyplot as plt
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Conv2D, Dropout, Flatten, MaxPooling2D
import numpy

(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()

print('\n\n\nstart')

for i in range(0, 10):
    image_index = 0 # You may select anything up to 60,000
    while True:
        if i == y_train[image_index]:
            #plt.imshow(x_train[image_index], cmap='Greys')
            #print('save', type(x_train[image_index]), x_train[image_index])
            plt.imsave(str(y_train[image_index]) + '.jpg', x_train[image_index])
            #print('read', plt.imread(str(y_train[image_index]) + '.png', ))
            #print('read', numpy.load(str(y_train[image_index]) + '.npy'))
            break
        else:
            image_index += 1
exit()

for i in range(0, 10):
    image_index = 0 # You may select anything up to 60,000
    while True:
        if i == y_train[image_index]:
            #plt.imshow(x_train[image_index], cmap='Greys')
            #print('save', type(x_train[image_index]), x_train[image_index])
            #plt.imsave(str(y_train[image_index]) + '.png', x_train[image_index])
            #print('read', plt.imread(str(y_train[image_index]) + '.png', ))
            numpy.save(str(y_train[image_index]) + '.npy', x_train[image_index])
            print('read', numpy.load(str(y_train[image_index]) + '.npy'))
            break
        else:
            image_index += 1
exit()

print('x_train.shape', type(x_train), x_train.shape, 'y_train.shape', type(y_train), y_train.shape)

# Reshaping the array to 4-dims so that it can work with the Keras API
x_train = x_train.reshape(x_train.shape[0], 28, 28, 1)
x_test = x_test.reshape(x_test.shape[0], 28, 28, 1)

x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
# Normalizing the RGB codes by dividing it to the max RGB value.
x_train /= 255
x_test /= 255
print('x_train shape:', x_train.shape)
print('Number of images in x_train', x_train.shape[0])
print('Number of images in x_test', x_test.shape[0])

model = Sequential()
input_shape = (28, 28, 1)
model.add(Conv2D(28, kernel_size=(3,3), input_shape=input_shape))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten()) # Flattening the 2D arrays for fully connected layers
model.add(Dense(128, activation=tf.nn.relu))
model.add(Dropout(0.2))
model.add(Dense(10, activation=tf.nn.softmax))

model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
model.fit(x=x_train,y=y_train, epochs=10)

model.evaluate(x_test, y_test)

image_index = 4444
#plt.imshow(x_test[image_index].reshape(28, 28),cmap='Greys')
pred = model.predict(x_test[image_index].reshape(1, input_shape[0], input_shape[1], 1))
print('predict result: ', pred.argmax()) # get 9
